#include "camera.h"

Camera::Camera(void) 
{

}

Camera::~Camera() 
{
    
}

bool Camera::initShm(char *shmName)
{
    int ret = -1;
    int fd = -1;
    bool bret = false;
 
    //创建或者打开一个共享内存
    fd = shm_open(shmName, OPEN_FLAG, OPEN_MODE);
    if(-1 == (ret = fd))
    {
        perror("shm  failed: ");
        return bret;
    }
     
     
    //调整确定文件共享内存的空间
    ret = ftruncate(fd, sizeof(MatBuf) * 20);
    if(-1 == ret)
    {
        perror("ftruncate faile: ");
        return bret;
    }
     
    //映射目标文件的存储区
    shareMatAddr = mmap(NULL, sizeof(MatBuf) * 20, PROT_READ, MAP_SHARED, fd, SEEK_SET);
    if(NULL == shareMatAddr)
    {
        perror("mmap src failed: ");
        return bret;
    }

    bret = true;
 
    return bret;
}

bool Camera::getNewMat(cv::Mat &mat)
{
    bool bret = false;
    unsigned int index = 0;

    bret = getNewMat(mat, index);

    return bret;
}

bool Camera::getNewMat(cv::Mat &mat, unsigned int &index)
{
    bool bret = false;

    MatBuf *p = (MatBuf *)shareMatAddr;
    unsigned int max = 0;
    static int maxIndex = -1;

    for(int i=0;i<20;i++)
    {
        if(p[i].counter > max)
        {
            max = p[i].counter;
            maxIndex = i;
        }
    }
    if(maxIndex == -1)
    {
        maxIndex = 0;
    }

    if(historyCounter != max)
    {
        cv::Mat img(1080, 1920, CV_8UC3, p[maxIndex].data);//浅拷贝
        mat = img.clone();
        // printf("get mat counter = %d\r\n", max);
        bret = true;
    }
    else
    {
        cv::Mat img(1080, 1920, CV_8UC3, p[maxIndex].data);//浅拷贝
        mat = img.clone();
    }

    index = maxIndex;
    historyCounter = max;

    return bret;
}

bool Camera::getMatByIndex(cv::Mat &mat, unsigned int index)
{
    bool bret = false;

    MatBuf *p = (MatBuf *)shareMatAddr;
    unsigned int max = 0;
    static int maxIndex = -1;

    for(int i=0;i<20;i++)
    {
        if(p[i].counter > max)
        {
            max = p[i].counter;
            maxIndex = i;
        }
    }
    if(maxIndex == -1)
    {
        maxIndex = 0;
    }

    if(maxIndex - index > 0 && maxIndex - index < 16)
    {
        cv::Mat img(1080, 1920, CV_8UC3, p[index].data);//浅拷贝
        mat = img.clone();
        bret = true;
    }

    return bret;
}
